const FileManagerPlugin = require('filemanager-webpack-plugin');
const userConfig = require('./userConfig.js');
// 自定义webpack插件
class CustomPlugin {
    constructor(mode) {
        this.config = { ...userConfig, mode };
    }
    apply(compiler) {
        if (['compress', 'copy'].includes(this.config.mode)) {
            console.log('执行自定义插件脚本');
            const config = {
                copyToDir: {
                    copy: [
                        { source: './rbp', destination: this.config.expressDir }
                    ],
                    delete: ['./rbp']
                },
                compressToDesktop: {
                    mkdir: [this.config.compressDir],
                    archive: [
                        {
                            source: `./rbp`,
                            destination: require('path').resolve(
                                this.config.compressDir,
                                `${this.config.fileName}.zip`
                            )
                        }
                    ],
                    delete: ['./rbp']
                },
                compress: {
                    archive: [{ source: `./rbp`, destination: `./rbp.zip` }],
                    delete: ['./rbp']
                }
            };
            compiler.options.plugins.push(
                new FileManagerPlugin({
                    onEnd: config[this.config.mode]
                })
            );
            if (['copyToDir', 'compressToDesktop'].includes(this.config.mode)) {
                compiler.plugin('emit', (compilation, callback) => {
                    const fileName = 'config.js';
                    if (compilation.assets[fileName]) {
                        const FileStream = `Window.config = {APIURL: '${this.config.configRequest}'};`;
                        compilation.assets[fileName] = {
                            source: function () {
                                return FileStream;
                            },
                            size: function () {
                                return FileStream.length;
                            }
                        };
                    }
                    callback();
                });
            }
        }
    }
}
const Host = () => {
    const interfaces = require('os').networkInterfaces();
    for (const devName in interfaces) {
        const iface = interfaces[devName];
        for (let i = 0; i < iface.length; i++) {
            const alias = iface[i];
            if (
                alias.family === 'IPv4' &&
                alias.address !== '127.0.0.1' &&
                !alias.internal
            ) {
                return alias.address;
            }
        }
    }
};
module.exports = {
    CustomPlugin,
    Host: Host()
};
